<template>
<div>
  <el-card>
    <!--搜索表单-->
    <div>
      <el-row>
        <el-form v-if="role_id != 3" ref="staffForm" :model="staffForm" label-width="85px" label-position="left">
          <el-col :span="8">
            <el-form-item label="员工姓名：">
              <el-input v-model="staffForm.realName" placeholder="请输入员工姓名" :clearable=true></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-form-item label="性别：">
              <el-select v-model="staffForm.sex" placeholder="请选择性别" :clearable=true>
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item>
              <template>
                <el-button type="success" size="small" @click="onSearch">搜索</el-button>
                <el-button size="small" @click="onReset('staffForm')">重置</el-button>
              </template>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>
    <!--  新增按钮-->
    <!-- <div class="content-header" v-if="role_id != 3">
      <el-button type="success" size="small" @click="handleAdd">新增员工</el-button>
    </div> -->
    <!--  表格-->
    <div>
      <div>
        <el-table :data="staffData" stripe style="width: 100%" :header-cell-style="{
      'background-color': '#fafafa',
      'color': 'rgb(103, 194, 58)',
      'border-bottom': '1px rgb(103, 194, 58) solid'}">
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="realName" label="员工姓名"></el-table-column>
          <el-table-column prop="tel" label="电话"></el-table-column>
          <el-table-column prop="birth" label="生日"  value-format="yyyy-MM-dd"></el-table-column>
          <el-table-column prop="sex" label="性别">
            <template slot-scope="scope">
              {{scope.row.sex === 0 ? '男':'女'}}
            </template>
          </el-table-column>
          <el-table-column prop="position" label="职务"></el-table-column>
          <el-table-column prop="aptName" label="公寓名称"></el-table-column>
          <el-table-column prop="roomId" label="房间号">
            <template slot-scope="scope">
              <span>
                <el-link type="primary">{{ scope.row.roomId}}</el-link>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="inTime" label="入住时间" width="150" value-format="yyyy-MM-dd"></el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text"  @click="editClick(scope.row)" class="editButton">编辑</el-button>
              <el-button v-if="role_id == 3" type="text"  @click="change(scope.row, 20)" class="viewButton">换房</el-button>
              <el-button v-if="role_id == 3" type="text"  @click="retreat(scope.row, 30)" class="editButton">退房</el-button>
              <el-button v-if="role_id != 3" type="text" @click="deleteClick(scope.row.id)" class="deleteButton">删除</el-button>
            </template>
          </el-table-column>

          <el-table-column v-if="role_id != 3" label="申请情况" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 0" type="success">无</el-tag>
              <el-tag v-else type="success" @click="option(scope.row)">{{scope.row.status == 10? '申请': scope.row.status == 20? '换房': '退房'}}</el-tag>
            </template>
          </el-table-column>

        </el-table>
      </div>
    </div>
    <!--  分页-->
    <div v-if="role_id != 3">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[8, 10, 15, 20]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      class="pagination-warp">
      </el-pagination>
    </div>
    <!--  编辑对话框-->
    <edit-staff ref="edit" @editCallBack="editBack"></edit-staff>
    <!--新增对话框组件-->
    <add-staff ref="add" @addCallBack="addBack"></add-staff>
  </el-card>

  <!-- 换房弹出对话框 -->
  <el-dialog
  :title="flag == 20? '换房': '退房'"
  :visible.sync="centerDialogVisible"
  width="60%"
  center>
    <el-form
      :model="changeRoom"
      ref="changeRoom"
      label-width="100px"
      :inline="true"
    >
      <el-form-item label="姓名：" prop="real_name">
        <el-input v-model="changeRoom.real_name"></el-input>
      </el-form-item>
      <el-form-item label="身份证号：" prop="id_card">
        <el-input v-model="changeRoom.id_card"></el-input>
      </el-form-item>
      <el-form-item label="公寓名称：" prop="apt_name">
        <el-select v-model="changeRoom.apt_id" placeholder="请选择" @change = "roomToApt($event)">
          <el-option
            v-for="item in apartment"
            :key="item.aptId"
            :label="item.aptName"
            :value="item.aptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房间编号：" prop="r_id">
        <el-select v-model="changeRoom.r_id">
          <el-option
              v-for="item in rooms"
              :key="item.id"
              :label="item.rid"
              :value="item.rid">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="flag == 20? '换房原因：': '退房原因：'" prop="reason_log">
        <el-input type="textarea" v-model="changeRoom.reason_log"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button type="success" @click="changeRoomSave">{{this.flag == 20? '换 房': '退 房'}}</el-button>
      <el-button @click="centerDialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>

  <!-- 管理员换房退房弹出框 -->
  <el-dialog
  :title="flag == 20? '换房': '退房'"
  :visible.sync="managerChangeRoom"
  width="60%"
  center>
    <!-- 显示弹出框的员工信息 -->
    <el-form
      :model="manageChange"
      label-width="100px"
      :inline="true"
    >
      <el-form-item label="姓名：" prop="real_name">
        <el-input v-model="manageChange.real_name"></el-input>
      </el-form-item>
      <el-form-item label="身份证号：" prop="id_card">
        <el-input v-model="manageChange.id_card"></el-input>
      </el-form-item>
      <el-form-item label="公寓名称：" prop="apt_name">
        <el-input v-model="manageChange.apt_name"></el-input>
      </el-form-item>
      <el-form-item label="房间编号：" prop="r_id">
        <el-input v-model="manageChange.r_id"></el-input>
      </el-form-item>
      <el-form-item :label="flag == 20? '换房原因：': '退房原因：'" prop="reason_log">
        <el-input type="textarea" v-model="manageChange.reason_log"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button type="success" @click="manageRoomSave">同 意</el-button>
      <el-button @click="managerChangeRoom = false">取 消</el-button>
    </span>
  </el-dialog>

</div>
</template>

<script>
import editStaff from "@/components/staff/editStaff";
import addStaff from "@/components/staff/addStaff";
export default {
name: "staff",
  data(){
    return{
      //判断是否有新的申请
      judge: {},
      //换房弹出对话框的控制
      changeRoom: {
        e_id: '',
        username: '',
        real_name: '',
        id_card: '',
        apt_id: '',
        apt_name: '',
        r_id: '',
        reason_log: ''
      },
      //公寓信息
      apartment: [],
      rooms: [],
      centerDialogVisible: false,
      managerChangeRoom: false,
      manageChange:{
        e_id: '',
        username: '',
        real_name: '',
        id_card: '',
        apt_id: '',
        apt_name: '',
        r_id: '',
        reason_log: ''
      },
      role_id:'',
      staffForm:{
        realName:'',
        gender:'',
      },
      staffData:[],
      pagenum:1,//当前页数
      pagesize:10,//当前页有多少条数据
      total:100,//总页数
      erId: 0,
      apt_id: 0,
      ruleId: 0,
      flag: 0//换房或者退房操作
    }
  },
  components:{editStaff,addStaff},
  created() {
    this.getUserList()
    //获取当前用户对应的角色
    this.getCurrentUserRule()
  },
  methods:{
    //获取数据
    async getUserList(){
      const {data:res} = await this.$http.get('/user/getEmployees',{params: {
        pageNum:this.pagenum,
        pageSize:this.pagesize
      }})
      if (res.code !== 200){
        return this.$message.error("获取用户信息失败")
      }
      this.staffData = res.data.list
      this.total = res.data.total
      console.log(this.staffData)
    },
    //获取当前用户角色对应的方法
    async getCurrentUserRule(){
      const {data:res} = await this.$http.post('/util/getJWTMessage', {
        "token": window.localStorage.getItem('token'),
        "keyName": "role_id"//获取的是当前角色对应的 role_id
      })
      this.role_id = res.data
    },
    //监听pagesize的改变事件
    handleSizeChange(newSize){
      console.log(newSize)
      this.pagesize=newSize
      this.getUserList()
    },
    //监听页码的变化
    handleCurrentChange(newPage){
      this.pagenum=newPage
      this.getUserList()
    },
    //搜索
    async onSearch(){
      const {data:res}= await this.$http.post('/user/getUserByEntity', {
        real_name: this.staffForm.realName,
        sex: this.staffForm.sex,
        rule_id: 3,//这个模块只能搜索员工
        pageNum:this.pagenum,
        pageSize:this.pagesize
      })
      this.staffData=res.data.list
      this.total = res.data.total
    },
    //换房
    async change(row, flag) {
      this.flag = flag
      //这里需要一个换房弹筐显示
      this.changeRoom.e_id = row.id
      this.changeRoom.username = row.username
      this.changeRoom.real_name = row.realName
      this.changeRoom.id_card = row.idCard
      this.changeRoom.apt_id = row.apt_id
      this.changeRoom.apt_name = row.aptName
      this.changeRoom.r_id = row.roomId
      //查询所有的公寓信息
      const {data:res}= await this.$http.post('/apartment/selectApartment',{})
      console.log(res.data)
      this.apartment = res.data//拿到公寓的信息显示
      this.centerDialogVisible = true
    },
    //保存房间的函数
    async changeRoomSave() {
      //先判断是否已经申请过
      const {data: r} = await this.$http.get('/erInformation/selectERInformationByIdOreIdOrrId',{params: {
        e_id: this.changeRoom.e_id,
        status: 0
      }})
      if(r.code == 200 && r.data == null) {
        const {data:res} = await this.$http.post('/erInformation/insertERInformation',{
          e_id: this.changeRoom.e_id,
          apply_status: this.flag,
          r_id: this.changeRoom.r_id,
          apt_id: this.changeRoom.apt_id,
          reason_log: this.changeRoom.reason_log,
          status: 0 //待处理状态
        })

        if(res.code == 200) {
          //改变 user 表中的状态
          const {data: result} = await this.$http.post('/user/updateUserByEntity',{
            id: this.changeRoom.e_id,
            status: this.flag//改变为更换状态
          })

          if(result.code == 200) {
            this.$message({
            type: 'success',
            message: '申请成功!'
          });
        }
        this.centerDialogVisible = false
        }
      } else {
        this.$message({
          type: 'error',
          message: '你已经申请过了!'
        })
      }
    },
    //退房
    async retreat(row, flag) {
      this.flag = flag
      //这里需要一个换房弹筐显示
      this.$confirm('您确定要申请退房吗?退房成功后账号将会被注销', '退房提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.changeRoom.e_id = row.id
        this.changeRoom.username = row.username
        this.changeRoom.real_name = row.realName
        this.changeRoom.id_card = row.idCard
        this.changeRoom.apt_id = row.apt_id
        this.changeRoom.apt_name = row.aptName
        this.changeRoom.r_id = row.roomId
        //查询所有的公寓信息
        const {data:res}= await this.$http.post('/apartment/selectApartment',{})
        console.log(res.data)
        this.apartment = res.data//拿到公寓的信息显示
        this.centerDialogVisible = true
      })
    },
    async roomToApt(event) {
      console.log(event)
      const {data: res} = await this.$http.get('/room/getRoomsByAptId', {
        params: {
          apt_id: event,
          status: 1
        }})

      console.log(res.data)
      this.rooms = res.data
      this.changeRoom.r_id = ''
    },
  //  重置
    onReset(){
      this.$refs.staffForm.resetFields()
      this.pagenum=1
      this.getUserList()
    },
  //  新增
    // handleAdd(){
    //   this.$refs.add.init()
    // },
  //  编辑
    editClick(row){
      console.log(row)
      this.$refs.edit.init(row)

    },
    //删除
    deleteClick(id){
      this.$confirm('您确定要删除吗?', '退房提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
      const {data:res} = await this.$http.post('/user/deleteUserById/'+id)
      if(res.code!==200) return this.$message.error('删除员工信息失败！')
      this.getUserList()
      }).catch(() => { this.$message({type: 'info', message: '已取消' }); });
    },
    //编辑对话框的回调函数
    editBack(){
      this.getUserList()
    },
    //新增对话框的回调函数
    addBack(){
      this.getUserList()
    },
    //操作
    async option(row) {
      const {data: res} = await this.$http.get('/erInformation/selectERInformationByIdOreIdOrrId', {
        params: {
          e_id: row.id,
          status: 0
        }
      });
      //标记状态
      this.flag = res.data.applyStatus

      this.erId = res.data.id
      this.manageChange.e_id = row.id
      this.manageChange.username = row.username
      this.manageChange.real_name = row.realName
      this.manageChange.id_card = row.idCard
      this.manageChange.apt_id = row.apt_id
      this.manageChange.apt_name = row.aptName
      this.manageChange.r_id = res.data.rid
      this.manageChange.reason_log = res.data.reasonLog
      this.managerChangeRoom = true
    },
    async manageRoomSave() {
      //换房操作
      if(this.flag == 20) {
        //如果保持就修改当前用户的房间号
        const {data: res} = await this.$http.post('/user/updateUserByEntity', {
          id: this.manageChange.e_id,
          apt_id: this.manageChange.apt_id,
          apt_name: this.manageChange.apt_name,
          room_id: this.manageChange.r_id
        });
        //如果房间号修改成功
        if(res.code == 200) {
          //修改状态
          await this.$http.post('/user/updateUserByEntity',{
            id: this.manageChange.e_id,
            status: 0
          })
          await this.$http.post('/erInformation/updateERInformation',{
            id: this.erId,
            status: 1
          })
          //刷新数据
          this.getUserList()
          this.managerChangeRoom = false
          this.$message({type: 'success', message: '修改成功！' });
        } else {
          this.$message({type: 'error', message: '修改失败！' });
        }
      } else {
        //退房操作
        const {data:res} = await this.$http.post('/user/deleteUserById/'+this.manageChange.e_id)
        if(res.code!==200) return this.$message.error('员工退房成功！')
        await this.$http.post('/erInformation/updateERInformation',{
          id: this.erId,
          status: 1
        })
        this.getUserList()
        this.managerChangeRoom = false
        this.$message({type: 'success', message: '退房成功！员工账号已注销' });
      }
    }
  },
}
</script>

<style scoped>

</style>